package com.xian.im.common.utils.bussiness;

import com.xian.im.common.model.dto.GroupDto;
import com.xian.im.common.model.session.SessionGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-01-28 21:51
 **/
public class GroupContextUtil {

    /**
     *  群组session
     */
    private static Map<String, SessionGroup> SESSION_GROUP_MAP = new ConcurrentHashMap<>();
    /**
     *  groupId  对应的 群组信道绑定
     */
    private static Map<String, ChannelGroup> CHANNEL_GROUPS = new ConcurrentHashMap<>();
    /**
     *  绑定群组
     * @param groupId
     * @param groupEntity
     */
    public static void build(String groupId, GroupDto groupEntity){
        SESSION_GROUP_MAP.put(groupId,SessionGroup.build(groupEntity));
    }
    /**
     *  绑定群组
     * @param groupId
     * @param sessionGroup
     */
    public static void build(String groupId, SessionGroup sessionGroup){
        SESSION_GROUP_MAP.put(groupId,sessionGroup);
    }
    /**
     * 获取群组Session
     * @param groupId
     * @return
     */
    public static SessionGroup getSessionGroup(String groupId){
        return SESSION_GROUP_MAP.get(groupId);
    }

    /**
     *  清理群组session
     * @param groupId
     */
    public static void   unBindGroupSession(String groupId){
        SESSION_GROUP_MAP.remove(groupId);
    }
    /**
     *  删除群组Session
     * @param groupId
     */
    public static void removeSessionGroup(String groupId){
        SESSION_GROUP_MAP.remove(groupId);
    }

    public static void clearChannelGroups(){
        CHANNEL_GROUPS.clear();
    }

    public static void clearSessionGroupMap(){
        SESSION_GROUP_MAP.clear();
    }

    public static ChannelGroup getGroupChannel(String groupId){
        ChannelGroup group =CHANNEL_GROUPS.get(groupId);
        if(null == group){
            synchronized (CHANNEL_GROUPS) {
                if(null == group){
                    group = new DefaultChannelGroup(groupId, GlobalEventExecutor.INSTANCE);
                    CHANNEL_GROUPS.put(groupId,group);
                }
            }
        }
        return group;
    }

    public static void init(Set<String> strings) {
        for (String groupId : strings) {
            ChannelGroup group = CHANNEL_GROUPS.get(groupId);
            if (null == group) {
                group = new DefaultChannelGroup(groupId, GlobalEventExecutor.INSTANCE);
                CHANNEL_GROUPS.put(groupId, group);
            }
        }
    }

    public static void destroy(String groupId){
        SESSION_GROUP_MAP.remove(groupId);
        SESSION_GROUP_MAP.remove(groupId);
    }
}
